package example.documentbased.editorModule.controller
{
	import example.documentbased.common.components.DecisionPopUp;
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.mainModule.controller.ICommonController;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	
	import flash.events.Event;
	
	import mx.collections.ArrayList;
	
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	import org.etherframework.controller.common.PopUpModel;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class CloseDocumentCommand extends ReactiveCommand
	{
		private var _editorModel:EditorModuleModel;
		private var _document:DocumentVO;
		private var _commonController:ICommonController;
		private var _editorController:IEditorController;
		private var _isSafe:Boolean;
		
		public function CloseDocumentCommand(editorModel:EditorModuleModel,
											 commonController:ICommonController, 
											 editorController:IEditorController)
		{
			super();
			
			_editorModel = editorModel;
			_commonController = commonController;
			_editorController = editorController;
		}
		
		public function initialize(document:DocumentVO, isSafe:Boolean):IReactiveCommand
		{
			_document = document;
			_isSafe = isSafe;
			markAsInitialized();
			
			return this;
		}
		
		override public function observable():IObservable
		{
			if (_isSafe && _editorModel.getIsEditedDocument(_document))
			{
				var model:PopUpModel = new PopUpModel("Save Document", "Document '"+_document.name+"' has been modified. Save changes?");
				
				return _commonController.getShowPopUpCommand(DecisionPopUp, model).observable()
				.mapMany(function(event:Event):IObservable
				{
					if (event.type == Event.COMPLETE)
					{
						var observable:IObservable = _document.id ? 
							_editorController.getSaveDocumentCommand(_document).observable() :
							_editorController.getSaveAsDocumentCommand(_document).observable();
							
						return observable.concatMany(function(id:String):IObservable
						{
							return onDocumentComplete();
						}); 
					}
					
					return onDocumentComplete();
				});
			}
			
			return onDocumentComplete();
		}
		
		private function onDocumentComplete():IObservable
		{
			_editorModel.closeDocument(_document);
			
			var openedDocuments:ArrayList = _editorModel.openedDocuments;
			
			if (openedDocuments.length)
			{
				var docToSelect:DocumentVO = DocumentVO(openedDocuments.getItemAt(openedDocuments.length - 1));
				return _editorController.getSetCurrentDocumentCommand(docToSelect).observable();
			}
			
			return Observable.value(new Unit());
		}
	}
}